<?php

namespace App\Http\Controllers;

use App\Http\Traits\CacheTrait;
use App\Http\Traits\GitLabTrait;
use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use Auth;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Validator;

class PermissionController extends Controller
{
    use CacheTrait, GitLabTrait;

    public function index()
    {
        return response()->json(Permission::all(), Response::HTTP_OK, [], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    }

    public function set(Request $request, $project_id, $setting_id)
    {
        if ($request->isMethod('post')) {
            $validator = Validator::make($request->all(), [
                'user_id' => 'sometimes|required|integer|exists:users,id',
            ]);

            if ($validator->fails()) {
                return back()->withErrors($validator);
            }

            $role_name = Role::getDeployRoleName($project_id, $setting_id);
            $role      = Role::whereName($role_name)->first();
            /** @var User $user */
            $user = User::find($request->get('user_id'));
            if (!$user) {
                abort(Response::HTTP_FORBIDDEN);
            }
            if (!$user->hasRole($role_name)) {
                $user->attachRole($role);
            } else {
                $user->detachRole($role);
            }

            $this->forgetProjects($request->get('user_id'));

            return back()->with(['success_msg' => '权限修改成功']);
        }

        /** @var User $user */
        $user = Auth::user();
        if (!$user->hasRole('owner')) {
            abort(Response::HTTP_FORBIDDEN);
        }

        $members = $this->getRepoMembers($project_id);
        $project = $this->getProject($project_id);
        if (isset($project['namespace']) && $project['namespace']['kind'] == 'group') {
            $group_id      = $project['namespace']['id'];
            $group_members = $this->getGroupMembers($group_id);
            if (is_array($group_members)) {
                $members = array_merge($members, $group_members);
            }
        }
        $members = collect($members);
        $ids     = $members->pluck('id');
        $users   = User::whereIn('gitlab_uid', $ids)->get();

        $permission_name = Permission::getDeployPermissionName($project_id, $setting_id);

        return view('permission/set')->with(['permission_name' => $permission_name, 'users' => $users, 'project_id' => $project_id]);
    }

    public function update($project_id, $setting_id, $user_id)
    {
    }

    public function create()
    {
        /*try {
            Permission::create([
                'name'         => Permission::DEPLOY_DEVELOPMENT,
                'display_name' => Permission::DEPLOY_DEVELOPMENT,
                'description'  => '部署 Dev 服务器',
            ]);
        } catch (QueryException $e) {
            dump($e->getMessage());
        }
        try {
            Permission::create([
                'name'         => Permission::DEPLOY_STAGING,
                'display_name' => Permission::DEPLOY_STAGING,
                'description'  => '部署 STAGING 服务器',
            ]);
        } catch (QueryException $e) {
            dump($e->getMessage());
        }
        try {
            Permission::create([
                'name'         => Permission::DEPLOY_PRODUCT,
                'display_name' => Permission::DEPLOY_PRODUCT,
                'description'  => '部署 PRODUCT 服务器',
            ]);
        } catch (QueryException $e) {
            dump($e->getMessage());
        }*/
    }
}
